package config

import (
	"encoding/json"
	"errors"
	"fmt"
	"gopkg.in/yaml.v2"
	"os"
)

var Config config

func Init(path string) {
	file, err := os.ReadFile(path)
	if err != nil {
		panic(err.Error())
	}
	err = yaml.Unmarshal(file, &Config)
	marshal, _ := json.Marshal(Config)
	fmt.Println(string(marshal))
	if err != nil {
		panic(err.Error())
	}
	err = check()
	if err != nil {
		panic(err)
	}
}

type config struct {
	Mode   string `yaml:"mode"`
	Secret string `yaml:"secret"`
	Net    struct {
		Bind string `yaml:"bind"`
		Port string `yaml:"port"`
	} `yaml:"net"`
	Mongo struct {
		Url      string                   `yaml:"url"`
		Username string                   `yaml:"username"`
		Password string                   `yaml:"password"`
		DB       string                   `yaml:"db"`
		Indexs   []map[string]interface{} `yaml:"indexs"`
	} `yaml:"mongo"`
	Mysql struct {
		Url      string                   `yaml:"url"`
		Username string                   `yaml:"username"`
		Password string                   `yaml:"password"`
		DB       string                   `yaml:"db"`
		Indexs   []map[string]interface{} `yaml:"indexs"`
	} `yaml:"mysql"`
	Redis struct {
		Url      string `yaml:"url"`
		Username string `yaml:"username"`
		Password string `yaml:"password"`
	} `yaml:"redis"`
	Plugin struct {
		Tourist struct {
			Mongo map[string]string `yaml:"mongo"`
			Mysql map[string]string `yaml:"mysql"`
			Redis map[string]string `yaml:"redis"`
		} `yaml:"tourist"`
		Task struct {
			Shell map[string]string `yaml:"shell"`
		}
	} `yaml:"plugin"`
	Log struct {
		Path string `yaml:"path"`
		Name string `yaml:"name"`
	}
	White []string `yaml:"white"`
}

func check() error {
	if &Config == nil {
		return errors.New("this config is not allowed")
	}
	if Config.Mode != "test" && Config.Mode != "debug" && Config.Mode != "release" {
		return errors.New("mode should in debug/test/release")
	}
	if Config.Log.Path == "" || Config.Log.Name == "" {
		return errors.New("log config is not allowed")
	}
	return nil
}
